package mi.payment.utils.iso8583;

import android.text.TextUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by KenMa on 2017/11/8.
 */

public class ParamsResolveUtils {

    private static Map<String, Integer> TagLenfthMap = new HashMap<>();

    static {
        TagLenfthMap.put("11", 2);//11  表示11 后面数据是2个字节
        TagLenfthMap.put("12", 2);
        TagLenfthMap.put("13", 1);
        TagLenfthMap.put("14", 14);
        TagLenfthMap.put("15", 14);
        TagLenfthMap.put("16", 14);
        TagLenfthMap.put("17", 14);
        TagLenfthMap.put("18", 1);
        TagLenfthMap.put("19", 2);
        TagLenfthMap.put("20", 1);
        TagLenfthMap.put("21", 1);
        TagLenfthMap.put("22", 40);
        TagLenfthMap.put("23", 1);
        TagLenfthMap.put("25", 1);
        TagLenfthMap.put("26", 4);
    }

    private static final int TAG_LEN = 4;

    public static Map<String, String> resolveParams(String hexStr) {
        if (TextUtils.isEmpty(hexStr)) {
            return null;
        }
        HashMap<String, String> resolveData = new HashMap<>();
        int pos = 0;
        int allLen = hexStr.length();
        while (pos + TAG_LEN < allLen) {
            String tag = hexStr.substring(pos, pos + TAG_LEN);
            tag = Utils.hexStr2AsciiStr(tag);
            pos += TAG_LEN;
            Integer LEN = TagLenfthMap.get(tag);
            if (LEN != null) {
                String value = hexStr.substring(pos, pos + 2 * LEN.intValue());
                pos += 2 * LEN.intValue();
                value = transfer(tag, value);
                resolveData.put(tag, value);
            }
        }
        return resolveData;
    }

    public static String transfer(String tag, String value) {
        if ("22".equals(tag)) {
            value = Utils.hexStr2AsciiStrGBK(value);
        } else if ("26".equals(tag)) {

        } else {
            value = Utils.hexStr2AsciiStr(value);
        }
        return value;
    }

    public static boolean getBitPos(String value, int pos) {
        byte[] bs = Utils.hexStr2Bytes(value);
        int data = bs[0] << 24 | bs[1] << 16 | bs[2] << 8 | bs[3];
        pos = 32 - pos;
        int des = 1 << pos;
        return (data & des) == des;

    }
}
